import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Checkbox, TreeSelect, Popconfirm, Select, Image } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { queryRule, updateRule, addRule, removeRule } from './service';
import FormItem from 'antd/lib/form/FormItem';
import { transTitle, handleReturnArray } from '@/utils/utils';
import UploadImg from '@/components/UploadImg';
import styles from '../../../../global.less';
import Access from '@/components/Access/Access';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在修改');
  try {
    await updateRule(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (fields, actionRef) => {
  const hide = message.loading('正在删除');
  try {
    await removeRule(fields);
    hide();
    actionRef.current.reload();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [FormValues, setFormValues] = useState({});
  const [authValues, setAuthValues] = useState([]);
  const [menuValues, setMenuValues] = useState([]);
  const [treeValue, handleTreeValue] = useState();
  const [checkedList, setCheckedList] = useState(authValues);
  const [facePicture, setFacePicture] = useState(null);
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const CheckboxGroup = Checkbox.Group;
  const handleSetFacePicture = (payload) => {
    setFacePicture(payload.url);
  };
  const TreeOnChange = (value) => {
    handleTreeValue(value);
  };

  const checkboxOnChange = (list) => {
    setCheckedList(list);
  };

  useEffect(() => {
    // handleQueryAuth({
    //   limit: 100,
    //   page: 1,
    // });
    // handleQueryMenu();
  }, []);

  /**
   * 查询角色
   * @param fields
   */
  // const handleQueryAuth = async (fields) => {
  //   try {
  //     const response = await queryAuth({ ...fields });
  //     const {
  //       data: { list = {} },
  //     } = response;
  //     let authArray = [];
  //     list.map((item, index) => {
  //       authArray.push(item.code);
  //     });
  //     let newArr = authArray.reduce((pre, cur) => {
  //       if (!pre.includes(cur)) {
  //         return pre.concat(cur);
  //       } else {
  //         return pre;
  //       }
  //     }, []);
  //     setAuthValues(newArr);
  //     return true;
  //   } catch (error) {
  //     return false;
  //   }
  // };

  const handleQueryMenu = async () => {
    try {
      const response = await queryRule({});
      const { data } = response;
      transTitle(data);
      setMenuValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'sort',
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '权限类型',
      dataIndex: 'type',
      valueEnum: {
        1: {
          text: '菜单',
          status: 'Processing',
          value: 1,
        },
        2: {
          text: '按钮',
          status: 'Default',
          value: 2,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} name="type" className="formItem_div">
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 3).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },

    {
      title: '父级',
      dataIndex: 'parentId',
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <TreeSelect
            showSearch
            // style={{ width: '400px' }}
            value={treeValue}
            dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
            placeholder="请选择父级"
            allowClear
            treeDataSimpleMode
            treeData={menuValues}
            treeNodeFilterProp="title"
            treeNodeLabelProp="title"
            onChange={TreeOnChange}
          />
        );
      },
    },
    {
      title: '路由',
      dataIndex: 'path',
      valueType: 'text',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      width: 200,
      hideInSearch: true,
      render: (_, payload) => {
        return <>{_ !== '-' ? <Image className={styles.img_div} src={_} /> : null}</>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {FormValues ? (
              <FormItem name="icon">
                <UploadImg
                  imgUrl={facePicture}
                  showImgUrl={facePicture}
                  subpath="icon"
                  handleSetFacePicture={handleSetFacePicture}
                />
              </FormItem>
            ) : (
              <FormItem name="icon">
                <UploadImg subpath="icon" handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            )}
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Access accessKey={"@updateResource"}>
            <a
              onClick={() => {
                handleQueryMenu();
                setFormValues(record);
                handleTreeValue(record.parentId);
                setFacePicture(record.icon);
                handleEditModalVisible(true);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
          </Access>
          <Access accessKey={"@deleteResource"}>
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="Yes"
              cancelText="No"
            >
              <a>删除</a>
            </Popconfirm>
          </Access>

        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        bordered
        toolBarRender={() => [
          <Access accessKey={"@newResource"}>
            <Button
              type="primary"
              onClick={() => {
                handleModalVisible(true);
                handleTreeValue(null);
                handleQueryMenu();
                setFacePicture();
              }}
            >
              <PlusOutlined /> 新增
            </Button>
          </Access>

          ,
        ]}
        pagination={false}
        options={false}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          return payload;
        }}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        title="添加列表"
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.parentId = treeValue;
            value.icon = facePicture;
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        width={800}
        title="修改菜单"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.parentId = treeValue ? treeValue : null;
            value.id = FormValues.id;
            value.icon = facePicture;
            const success = await handleUpdate(value);

            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            initialValues: FormValues,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
